package com.yty.demo._7_thread;

/**
 * @author: yangtaoyao
 * @time: 2020/1/14 13:14
 * @description: 生产者消费者
 */
public class ConsumerAndProvider {
    public static void main(String[] args) {
        Clerk c=new Clerk();

        //生产者
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (c){
                    while(true){
                        try {
                            if(c.productNum==0){
                                System.out.println("产品数为"+ c.productNum+"，开始生产");
                                c.productNum++;
                                System.out.println("库存："+c.productNum);
                                Thread.sleep(3000);
                                while(c.productNum<4){
                                    c.productNum++;
                                    System.out.println("库存："+c.productNum);
                                }
                                System.out.println("产品数为"+ c.productNum+",结束生产");
                                c.notify();
                            }else{
                                c.wait();
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (c){
                    while(true){
                        try{
                            if(c.productNum!=0){
                                System.out.println("产品数为"+c.productNum + "，开始消费");
                                c.productNum--;
                                System.out.println("库存："+c.productNum);
                                Thread.sleep(3000);
                                while(c.productNum>0){
                                    c.productNum--;
                                    System.out.println("库存："+c.productNum);
                                }
                                System.out.println("产品数为"+ c.productNum+",结束消费");
                                c.notify();
                            }else{
                                c.wait();
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }).start();
    }
}

class Clerk{
    public static int productNum=50;
}
